<?php

/**
* Created by PhpStorm.
* User: dumbledore
* Date: 2018/2/26
* Time: 下午4:42
*/
class multiple_address extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation');//加载表单验证类库 
        $this->load->helper('json');
        $this->load->helper('common');
        $this->load->model('user_model');
        $this->load->model('upload_model');
        $this->load->model('customer_model');
        $this->load->model('excel_model');
        $this->load->model('cart_model');
        $this->load->model('member_model');
        $this->load->model('goods_model');
        $this->load->library('email');
        $this->load->library('session');
    }

// 多地址上传页面
    public function index()
    {
        $customer_info = $this->session->customer_info;
        if ($customer_info['identity'] != 1) {
            redirect('multiple_address/no_permission_index');
        }
        $this->load->view('multiple_address/index');
    }

    // 无权查看页面
    public function no_permission_index()
    {
        $this->load->view('multiple_address/no_permission_index.php');
    }


// 多地址下单页面
    public function detail()
    {
        $customer_info = $this->session->customer_info;
        $customer_id = $this->session->customer_id;
        if ($customer_info['identity'] != 1) {
            redirect('multiple_address/no_permission_index');
        }
        if(isset($_GET['path']) && $_GET['path'] != "" && isset($_GET['name']) && $_GET['name'] != ""){
            $path = $this->config->item("upload_path").'/'.$_GET['path'];
        }else{
            $this->session->set_flashdata('msg', '请选择上传excel');
            redirect(base_url().'multiple_address');
        }

        $data = $this->excel_model->execExcel($path);

        foreach ($data as $key => $info) {
            $address = $this->cart_model->address();
            $district_id = "wu";
            foreach ($address as $value) {
                foreach ($value as $k => $v) {
                    if($v ==  $info[2]){
                        $province_id = $k;
                        foreach ($address[$province_id] as $ko => $vo) {
                            if($vo == $info[3]){
                                $city_id = $ko;
                                foreach ($address[$city_id] as $ke => $ve) {
                                    if($ve == $info[4]){
                                        $district_id = $ke;
                                    }
                                }
                            }
                        }
                    }

                } 
            }
            //获取地址的region_id
            if($info[3] == '天津_市辖区' || $info[3] == '北京_市辖区' || $info[3] == '上海_市辖区' || $info[3] == '重庆_市辖区'){
                $info[3] = '市辖区';
            }elseif($info[3] == '天津_县' || $info[3] == '北京_县' || $info[3] == '上海_县' || $info[3] == '重庆_县'){
                $info[3] = '县';
            }

            $list[$key]['address_compromise'] = trim($info[0]) . ';' . trim($info[1]) . ';' . trim($info[2]) . ';' . trim($info[3]) . ';' . trim($info[4]) . ';' . trim($info[5]). ';' .trim($district_id);
            $list[$key]['goods_id'] = $info[6];
            $list[$key]['goods_num'] = $info[7];
            $list[$key]['region_id'] = $district_id;
//$site['address'][] = $info[0] . ';' . $info[1] . ';' . $info[2] . ';' . $info[3] . ';' . $info[4] . ';' . $info[5] . ';' .$district_id;
        }

// foreach ($site as $key => $value) {
//    foreach (array_flip($value) as $k => $v) {
//        $addr[] = $k;
//    } 
// }

// foreach ($addr as $key => $value) {
//     $addrArr = explode(';', $value);
// }

        $tmp=array();
        $a=array();
        foreach ($list as $key => $value) {
            $a[$key]=false;
            foreach ($tmp as $m => $n) {
                if ($value['address_compromise'] == $m) {
                    if(isset($n[$value['goods_id']])){
                        $tmp[$m][$value['goods_id']]['goods_num'] +=$value['goods_num'];
                    }else{
                        $tmp[$m][$value['goods_id']]=$value;
                    }
                    $a[$key]=true;
                }

            }
            if($a[$key]!=true){
                $tmp[$value['address_compromise']][$value['goods_id']]=$value;
            }
// $tmp[$value['address_compromise']]=$value;
        }
        $item = array();
        $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($customer_id);
        foreach ($tmp as $key => $value) {
            foreach ($value as $k => $v) {
                unset($v['address_compromise']);
                $data = $this->goods_model->company_goods_infoes($v['goods_id'],$admin_shop_user_id);
                $v['goods_name'] = $data[0]['goods_name'];
                $v['goods_main_img'] = $data[0]['goods_main_img'];
                if($data[0]['adjust_price']){
                    $v['goods_price'] = $data[0]['adjust_price'];
                } else {
                    $v['goods_price'] = $data[0]['goods_price'];
                }
                
                $v['goods_attr'] = $data[0]['goods_attr'];
                $item[$key][] = $v;
            }   

        }

        $data['item'] = $item;
        $data['name'] = $_GET['name'];

        $this->load->view('multiple_address/detail',$data);
    }


//提交商品到购物车
    public function submit()
    {
        $customer_info = $this->session->customer_info;
        if ($customer_info['identity'] != 1) {
            redirect('multiple_address/no_permission_index');
        }
        $customer_id = $this->session->customer_id;
        $post = $this->input->post();
        $where = array('customer_id'=>$customer_id);
        $address_matching_arr = $this->db->where($where)->from('app_company')->get()->row_array();
        $addressMatchingArr = array();
        if($address_matching_arr){
            $addressMatchingArr[] = $address_matching_arr['shipping_name'].';'.$address_matching_arr['shipping_tel'].';'.$address_matching_arr['shipping_province'].';'.$address_matching_arr['shipping_city'].';'.$address_matching_arr['shipping_district'].';'.$address_matching_arr['shipping_address'];
            $addressMatchingArr[] = $address_matching_arr['shipping_name_second'].';'.$address_matching_arr['shipping_tel_second'].';'.$address_matching_arr['shipping_province'].';'.$address_matching_arr['shipping_city'].';'.$address_matching_arr['shipping_district'].';'.$address_matching_arr['shipping_address'];
        }
        if (!$post) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        } else {
            if (!$this->session->customer_id) {
                send_json(array('code' => -2, 'data' => '', 'msg' => "请先重新登录"));
            } else {
                if ($post['data']) {
                    $this->db->where(array('customer_id'=>$customer_id))->delete('app_temp_address_order');
                    $shop_address_id_arr = [];
                    foreach ($post['data'] as $key => $value) {
                        $arr = explode(';', $value);
                        if($arr[3] == '天津_市辖区' || $arr[3] == '北京_市辖区' || $arr[3] == '上海_市辖区' || $arr[3] == '重庆_市辖区'){
                            $arr[3] = '市辖区';
                        }
                        if($arr[3] == '天津_县' || $arr[3] == '北京_县' || $arr[3] == '上海_县' || $arr[3] == '重庆_县'){
                            $arr[3] = '县';
                        }
                        $address_matching = $arr[0] . ';' . $arr[1] . ';' . $arr[2] . ';' . $arr[3] . ';' . $arr[4] . ';' . $arr[5];

                        $where = array(
                            'customer_id' => $customer_id,
                            'name' => $arr[0],
                            'phone' => $arr[1],
                            'province' => $arr[2],
                            'city' => $arr[3],
                            'district' => $arr[4],
                            'address' => $arr[5]
                        );
                        $res = $this->db->where($where)->from('app_address')->get()->row_array();
                        if($res){
                            $shop_address_id = $res['shop_id'];
                        }else{
                            $data['customer_id'] = $customer_id;
                            $data['name'] = $arr[0];
                            $data['phone'] = $arr[1];
                            $data['province'] = $arr[2];
                            $data['city'] = $arr[3];
                            $data['district'] = $arr[4];
                            $data['address'] = $arr[5];
                            $data['region_id'] = $arr[6];
                            $this->db->insert('app_address',$data);
                            $id = $this->db->insert_id();
                            $data_sync['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
                            $data_sync['postcode'] = "";
                            $data_sync['name'] = $arr[0];
                            $data_sync['region_id'] = $arr[6];
                            $data_sync['address'] = $arr[5];
                            $data_sync['phone'] = $arr[1];
                            $data_sync['region_name'] = $arr[4];
                            $shop_address_id = $this->member_model->company_user_address($data_sync);
                            $this->db->where(array("id" => $id))->update('app_address', array('shop_id' => $shop_address_id));
                        }
                        $goods_id_num = explode(',', $arr[7]);
                        $goodsArr = [];
                        foreach ($goods_id_num as $k => $v) {
                            $goodArr = explode(':', $v);
                            $goodsArr[$goodArr[0]] = $goodArr[1];    
                        }
                        $ids = json_encode($goodsArr);

                        $item['customer_id'] = $customer_id;
                        $item['ids'] = $ids;
                        $item['address_id'] = $shop_address_id;
                        $item['time'] = time();
                        $bool = $this->db->insert('app_temp_address_order',$item);

                        if(!in_array($address_matching, $addressMatchingArr)){
                            $shop_address_id_arr[] = $shop_address_id;
                        }
                    }
//将$shop_address_id_arr保存session
                    $this->session->set_userdata('shop_address_id_arr',json_encode($shop_address_id_arr));
                    if($bool){
                        send_json(array('code' => 0, 'data' => '', 'msg' => ""));
                    }
                } else {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "请先选择商品"));
                }
            }
        }
    }

// 下单页面
    public function order()
    {
        $customer_info = $this->session->customer_info;
        if ($customer_info['identity'] != 1) {
            redirect('multiple_address/no_permission_index');
        }
        $customer_id = $this->session->customer_id;
        $item = array();
        $list = $this->db->where(array('customer_id'=>$customer_id))->from('app_temp_address_order')->get()->result_array();
        foreach ($list as $key => $value) {
            $ids = json_decode($value['ids'],'true');

            foreach ($ids as $k => $v) {
                $row['product_id'] =  $k;
                $row['number'] =  $v;

                $item[$key]['goodsinfo'][] = $row;

                $item[$key]['address_id'] = $value['address_id'];
            }
        }
        $rows['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
        $rows['list'] = json_encode($item);

        $result = $this->member_model->multiple_address_postage_scope($rows);
        foreach ($result as $key => $value) {
            $where = array('shop_id'=>$value['address_id']);
            $address = $this->db->where($where)->from('app_address')->get()->row_array();
            $result[$key]['name'] = $address['name'];
            $result[$key]['province'] = $address['province'];
            $result[$key]['city'] = $address['city'];
            $result[$key]['district'] = $address['district'];
            $result[$key]['address'] = $address['address'];
            $result[$key]['phone'] = $address['phone'];
        }

        $data['result'] = $result;

        $data['cost_center'] = $this->customer_model->get_admin_cost_center($customer_id);
        $data['customer_id'] = $customer_id;
        $this->load->view('multiple_address/order',$data);
    }

//提交订单
    public function create()
    {
        $customer_info = $this->session->customer_info;
        if ($customer_info['identity'] != 1) {
            redirect('multiple_address/no_permission_index');
        }
        $customer_id = $this->session->customer_id;
        $post = $this->input->post();
        $re = $this->db->query('select query_admin_id(' . $customer_id . ') as admin_id')->row_array();
        $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($customer_id);
        $data['list'] = $post['item'];
        $data['invoice_id'] = $post['invoice_id'];
        $data['type'] = $post['type'];
        $data['invoice_cont'] = $post['invoice_cont'];
        $result = $this->member_model->creat_moreorder_to_mall($data);

        if($result){
            if($result['count'] == 0){
                send_json(array('code' => -2, 'data' => $result['unsuccess_address_ids'], 'msg' => "生成订单失败"));
            }else if($result['count'] != 0 && $result['unsuccess_address_ids'] != ""){
                $this->db->where(array('customer_id'=>$customer_id))->delete('app_temp_address_order');
                $idsArr = explode(',', explode('=', $result['url'])[1]);
                foreach ($idsArr as $key => $value) {
                    $where = array('customer_id'=>$customer_id,'shop_order_id'=>$value);
                    $bool = $this->db->where($where)->update('app_order',array('cost_center_id'=>$post['cost_center_id'],'admin_customer_id'=>$re['admin_id']));
                }

                $order_ids_address_ids_arr = json_decode($result['success_arr'],true);
                $address_ids_arr = json_decode($this->session->shop_address_id_arr,true);
                if(count($order_ids_address_ids_arr) != 0 && count($address_ids_arr) != 0){
                    foreach ($order_ids_address_ids_arr as $key => $value) {
                        foreach ($address_ids_arr as $k => $v) {
                            if($value == $v){

                                $where = array('customer_id'=>$customer_id,'shop_order_id'=>$key); 

                                $bool2 = $this->db->where($where)->update('app_order',array('address_alert'=>1));

                            }
                        }
                    }
                }

                if($bool){
                    send_json(array('code' => -1, 'url' => $result['url'], 'data' => $result['unsuccess_address_ids'], 'msg' => "存在地址商品生成订单失败"));
                }

            }else{
                $this->db->where(array('customer_id'=>$customer_id))->delete('app_temp_address_order');
                $idsArr = explode(',', explode('=', $result['url'])[1]);
                foreach ($idsArr as $key => $value) {
                    $where = array('customer_id'=>$customer_id,'shop_order_id'=>$value);
                    $bool = $this->db->where($where)->update('app_order',array('cost_center_id'=>$post['cost_center_id'],'admin_customer_id'=>$re['admin_id']));
                }
                $order_ids_address_ids_arr = json_decode($result['success_arr'],true);
                $address_ids_arr = json_decode($this->session->shop_address_id_arr,true);
                if(count($order_ids_address_ids_arr) != 0 && count($address_ids_arr) != 0){
                    foreach ($order_ids_address_ids_arr as $key => $value) {
                        foreach ($address_ids_arr as $k => $v) {
                            if($value == $v){

                                $where = array('customer_id'=>$customer_id,'shop_order_id'=>$key); 

                                $bool2 = $this->db->where($where)->update('app_order',array('address_alert'=>1));

                            }
                        }
                    }
                }

                if($bool){
                    send_json(array('code' => 0, 'url' => $result['url'], 'msg' => "生成订单成功"));
                }

            }
        }
    }

// 解析excel内容
    public function analyze_multi_address_excel()
    {
        $customer_info = $this->session->customer_info;
        if ($customer_info['identity'] != 1) {
            redirect('multiple_address/no_permission_index');
        }
        $max_size = 20480;
        $path = $this->config->item("upload_path");
        $data = $this->upload_model->setType('all')->do_upload('file', $path, true, true, $max_size);

        if ($data['status'] == 0) {
            $this->db->trans_begin();

            $user_id = $this->session->customer_id;
            $is_account = $this->db->where(array('customer_id'=>$user_id))->from('app_admin')->get()->row_array()['is_account'];
            if ($user_id) {
                $excel_name = $data['data']['upload_data']['file_name'];
                $path = $path.'/'.$data['data']['upload_data']['file_name'];
                $data = $this->excel_model->execExcel($path);
                if(count($data) == 0){
                    $msg = '上传的excel不可为空';
                    $this->session->set_flashdata('multiple_address_alert', $msg);
                    redirect(base_url().'multiple_address/index');
                }
                $where = array('customer_id'=>$user_id);
                $address_matching_arr = $this->db->where($where)->from('app_company')->get()->row_array();
                $addressMatchingArr = array();
                if($address_matching_arr){
                    $addressMatchingArr[] = $address_matching_arr['shipping_name'].';'.$address_matching_arr['shipping_tel'].';'.$address_matching_arr['shipping_province'].';'.$address_matching_arr['shipping_city'].';'.$address_matching_arr['shipping_district'].';'.$address_matching_arr['shipping_address'];
                    $addressMatchingArr[] = $address_matching_arr['shipping_name_second'].';'.$address_matching_arr['shipping_tel_second'].';'.$address_matching_arr['shipping_province'].';'.$address_matching_arr['shipping_city'].';'.$address_matching_arr['shipping_district'].';'.$address_matching_arr['shipping_address'];
                }

                $all_num = 0;
                $all_goods = array();
                $all_records = array();
                $address_compromise = array();
                $is_address_maching = 0;
                $error_message = array();
                $admin_shop_user_id = $this->user_model->customer_id_to_admin_to_shop_user_id($user_id);
                // $data 分析
                foreach ($data as $key => $info) {
                    $line = $key + 2;
                    $goods_detail = $this->goods_model->company_goods_infoes($info[6],$admin_shop_user_id);
                    if (!$info[0]) {
                        $msg = '第' . $line . '行 收货人姓名不能为空';
                        $error_message[] = $msg;
                    } 
                    if (!$info[1]) {
                        $msg = '第' . $line . '行 收货人电话不能为空';
                        $error_message[] = $msg;
                    } 
                    if (!is_mobile($info[1])) {
                        $msg = '第' . $line . '行 手机号码不正确';
                        $error_message[] = $msg;
                    } 
                    if (!($info[2])) {
                        $msg = '第' . $line . '行 省不能为空';
                        $error_message[] = $msg;
                    } 
                    if (!($info[3])) {
                        $msg = '第' . $line . '行 市不能为空';
                        $error_message[] = $msg;
                    } 
                    if (!($info[4])) {
                        $msg = '第' . $line . '行 区不能为空';
                        $error_message[] = $msg;
                    } 
                    if (!($info[5])) {
                        $msg = '第' . $line . '行 地址不能为空';
                        $error_message[] = $msg;
                    } 
                    if(strlen($info[5])<6 || strlen($info[5])>60){
                        $msg = '地址最少要6个字，最多不能超过60个字';
                        $error_message[] = $msg;
                    }

                    if(preg_match('/^[0-9]+$/', $info[5]) || preg_match('/^[a-z]+$/', $info[5]) || preg_match('/^[A-Z]+$/', $info[5])){
                        $msg = '地址最少要6个字，最多不能超过60个字';
                        $error_message[] = '不能全为数字或字母';
                    };
                    if (!($info[6])) {
                        $msg = '第' . $line . '行 货号不能为空';
                        $error_message[] = $msg;
                    } 
                    if (count($goods_detail) == 0) {
                        $msg = '第' . $line . '行 货号错误，商品不存在';
                        $error_message[] = $msg;
                    } 
                    if (!($info[7])) {
                        $msg = '第' . $line . '行 商品数量不能为空';
                        $error_message[] = $msg;
                    } 
                    if (!is_numeric($info[7]) || $info[7]<0 || strpos($info[7],".")!==false) {
                        $msg = '第' . $line . '行 商品数量填写错误';
                        $error_message[] = $msg;
                    } 
                    if($info[7]>10000){
                        $msg = '第' . $line . '行 商品数量不可超过200件';
                        $error_message[] = $msg;
                    }
                    //获取地址的region_id
                    if($info[3] == '天津_市辖区' || $info[3] == '北京_市辖区' || $info[3] == '上海_市辖区' || $info[3] == '重庆_市辖区'){
                        $info[3] = '市辖区';
                    }elseif($info[3] == '天津_县' || $info[3] == '北京_县' || $info[3] == '上海_县' || $info[3] == '重庆_县'){
                        $info[3] = '县';
                    }

                    //判断地址是否匹配。
                    $address_matching = trim($info[0]) . ';' . trim($info[1]) . ';' . trim($info[2]) . ';' . trim($info[3]) . ';' . trim($info[4]) . ';' . trim($info[5]);
                    if(!in_array($address_matching, $addressMatchingArr)){
                        $is_address_maching = 1;
                    }

//最多支持10个地址
                    $address_compromise[] = trim($info[0]) . ';' . trim($info[1]) . ';' . trim($info[2]) . ';' . trim($info[3]) . ';' . trim($info[4]) . ';' . trim($info[5]);

//所有商品总和不得超过200个
                    $all_num += $info[7];


                    $address = $this->cart_model->address();
                    $district_id = "wu";
                    foreach ($address as $value) {
                        foreach ($value as $k => $v) {
                            if($v ==  $info[2]){
                                $province_id = $k;
                                foreach ($address[$province_id] as $ko => $vo) {
                                    if($vo == $info[3]){
                                        $city_id = $ko;
                                        foreach ($address[$city_id] as $ke => $ve) {
                                            if($ve == $info[4]){
                                                $district_id = $ke;
                                            }
                                        }
                                    }
                                }
                            }

                        } 
                    }
                    if($district_id =="wu"){
                        $msg = '第' . $line . '行 没有匹配到相应的地址';
                        $error_message[] = $msg;
                    }

//最多可以购买500种不同规格的商品
// if(!in_array($info[6], $all_goods)){
//     $all_goods[] = $info[6];
// }


// if(count($all_goods) > 500){
//     $msg = '最多可以购买500种不同规格的商品';
//     $this->session->set_flashdata('msg', $msg);
//     redirect(base_url().'multiple_address/index');
// }
//全部规格商品总购买件数最多50000件
// $all_num += $info[7];
// if($all_num>50000){
//     $msg = '全部规格商品总购买件数最多50000件';
//     $this->session->set_flashdata('msg', $msg);
//     redirect(base_url().'multiple_address/index');
// }



//每个收件地址购买一种规格的商品记录为一条，最多支持导入3000条
// $all_records[$district_id][] = $info[6];

// foreach ($all_records as $k => $v) {  
//     $array = array_flip($v);
//     $res[$k] = array_keys($array);
// }  
// $count = 0;
// foreach ($res as $k => $v) {
//     $count += count($v);
// }
// if($count>3000){
//     $msg = '每个收件地址购买一种规格的商品记录为一条，最多支持导入3000条';
//     $this->session->set_flashdata('msg', $msg);
//     redirect(base_url().'multiple_address/index');
// }
                }
                if($all_num>200){
                    $msg = '所有商品总和不得超过200个';
                    $error_message[] = $msg;
                }
                if(count(array_flip($address_compromise)) > 10){
                    $msg = '最多支持10个地址';
                    $error_message[] = $msg;
                }
            } else {
                $error_message[] = '请先登录';
            }

            if(count($error_message) != 0){
                $this->session->set_flashdata('multiple_address_alert',$error_message);
                redirect(base_url().'multiple_address/index');
            }
      
            if($is_address_maching == 1 && $is_account == 1){
                $msg = base_url().'multiple_address/detail?path='.$excel_name.'&name='.$_FILES['file']['name'];
                $this->session->set_flashdata('multiple_address_matching',$msg);
                redirect(base_url().'multiple_address/index');
            }



            $this->db->trans_commit();
//$this->session->set_flashdata('msg', '提交成功');
            redirect(base_url().'multiple_address/detail?path='.$excel_name.'&name='.$_FILES['file']['name']);

        } else {
            $this->session->set_flashdata('multiple_address_alert', '上传失败!' . $data['data']['error']);
            redirect(base_url().'multiple_address/index');
        }

    }

}